package com.ysjy.course.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.dto.course.CourseClassDto;
import com.wkbb.common.dto.course.CourseTimeDto;
import com.wkbb.common.utils.StringUtil;
import com.ysjy.course.dto.TeacherCourseTimeFeedbackDto;
import com.ysjy.course.model.*;
import com.ysjy.course.service.CourseClassService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(description = "小程序课班管理")
@RequestMapping("/course/class/user")
@Slf4j
public class CourseClassController extends BaseController {

    @Autowired
    private CourseClassService courseClassService;

    @ApiOperation(value = "获取新消息数量(count)")
    @RequestMapping(value = "getMessageCount", method = RequestMethod.GET)
    public ResultDTO<Map<String, Object>> getMessageCount(
            @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId
    ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(studentId)){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            Map<String, Object> data = courseClassService.getMessageCount(params);
            return ResultDTO.successResult(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "获取消息详情（状态转为已读）")
    @RequestMapping(value = "getMessage", method = RequestMethod.GET)
    public ResultDTO<YsMessage> getMessage(
            @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId,
            @ApiParam(value = "消息ID", required = false) @RequestParam(name = "id", required = false) Long id
    ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(studentId)){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            YsMessage data = courseClassService.getMessage(studentId,id);
            return ResultDTO.successResult(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "获取消息分页列表")
    @RequestMapping(value = "getMessageListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<YsMessage>> getMessageListByPage(
            @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize
    ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(studentId)){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            PageInfo<YsMessage> pageInfo = courseClassService.getMessageListByPage(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "我的课班列表")
    @RequestMapping(value = "getCourseClassList", method = RequestMethod.GET)
    public ResultDTO<List<CourseClassDto>> getCourseClassList(
            @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId,
            @ApiParam(value = "班级类型 4课程班 5托管班", required = false) @RequestParam(name = "classType", required = false) Integer classType) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(studentId)){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            params.put("classType", classType);
            List<CourseClassDto> list = courseClassService.getCourseClassListByStudent(params);
            for (CourseClassDto dto:list){
                dto.initStatus();
            }
            return ResultDTO.successResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "获取课班详情")
    @RequestMapping(value = "getCourseClass", method = RequestMethod.GET)
    public ResultDTO<CourseClassDto> getCourseClass(
            @ApiParam(value = "课班classId", required = false) @RequestParam(name = "classId", required = true) Integer classId) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return courseClassService.getCourseClass(classId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "我的课表")
    @RequestMapping(value = "getCourseTimeList", method = RequestMethod.GET)
    public ResultDTO<List<CourseTimeDto>> getCourseTimeList(
            @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId,
            @ApiParam(value = "服务标识（机构课程uniqueId or 托管uniqueId）", required = false) @RequestParam(name = "serviceUniqueId", required = false) String serviceUniqueId,
            @ApiParam(value = "日期 例：2022-06-20", required = false) @RequestParam(name = "date", required = false) String date
            ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(studentId)){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            if (!StringUtil.isEmpty(date)) params.put("date", date);
            if (!StringUtil.isEmpty(serviceUniqueId)) params.put("serviceUniqueId", serviceUniqueId);
            List<CourseTimeDto> list = courseClassService.getCourseTimeList(params);
            return ResultDTO.successResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "获取课表（指定月份哪些天有课）")
    @RequestMapping(value = "getHaveClassByMonth", method = RequestMethod.GET)
    public ResultDTO<List<String>> getHaveClassByMonth(
            @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId,
            @ApiParam(value = "月份 例：2022-06", required = true) @RequestParam(name = "month", required = true) String month
    ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(studentId)){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            if (!StringUtil.isEmpty(month)) params.put("month", month);
            List<String> list = courseClassService.getHaveClassByMonth(params);
            return ResultDTO.successResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "获取课表月统计（总数量（count）,已上课数量(haveCount)，待上课（count-haveCount））")
    @RequestMapping(value = "getCourseTimeCountByMonth", method = RequestMethod.GET)
    public ResultDTO<Map<String, Object>> getCourseTimeCountByMonth(
            @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId,
            @ApiParam(value = "月份 例：2022-06", required = true) @RequestParam(name = "month", required = true) String month
            ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(studentId)){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            if (!StringUtil.isEmpty(month)) params.put("month", month);
            Map<String, Object> data = courseClassService.getCourseTimeCountByMonth(params);
            return ResultDTO.successResult(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "可调课班列表")
    @RequestMapping(value = "getAdjustableCourseClassList", method = RequestMethod.GET)
    public ResultDTO<List<CourseClassDto>> getAdjustableCourseClassList(
            @ApiParam(value = "机构ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "当前班级ID", required = true) @RequestParam(name = "classId", required = true) Long classId
    ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("orgId", orgId);
            //可以报名
            params.put("canSignUp", true);
            params.put("classId", classId);
            List<CourseClassDto> list = courseClassService.getListByMapParams(params);
            for (CourseClassDto dto:list){
                dto.initStatus();
            }
            return ResultDTO.successResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "学生申请调班")
    @RequestMapping(value = "applyChangeClass", method = RequestMethod.POST)
    public ResultDTO<Boolean> applyChangeClass(
            @ApiParam(value = "学生报名id", required = true) @RequestParam(name = "signUpUserId", required = true) Long signUpUserId,
            @ApiParam(value = "新班级id", required = true) @RequestParam(name = "newClassId", required = true) Long newClassId,
            @ApiParam(value = "调班原因", required = false) @RequestParam(name = "way", required = false) String way
    ){
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return courseClassService.applyChangeClass(signUpUserId,newClassId,way);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "学生课时请假",notes = "{\"courseTimeId\":551,\"studentId\":1272392,\"leaveReason\":\"原因\",\"leaveExplain\":\"补充说明\"}")
    @RequestMapping(value = "putCourseTimeLeave", method = RequestMethod.POST)
    public ResultDTO<Boolean> putCourseTimeLeave(
            @Valid @RequestBody CourseAttendLeave data){
        try {
            UserDto userDto = this.getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (data.getStudentId() == null || data.getCourseTimeId() == null){
                return new ResultDTO(ErrorCode.PARAM_MISSING);
            }
            return courseClassService.putCourseTimeLeave(data);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.errorResult(e.getMessage());
        }
    }

    @ApiOperation(value = "学生课时评价（课堂反馈）",notes = "{\"courseTimeId\":551,\"studentId\":1272392,\"likeability\":9,\"satisficing\":9,\"interact\":9,\"teaching\":9}")
    @RequestMapping(value = "putCourseTimeFeedback", method = RequestMethod.POST)
    public ResultDTO<Boolean> putCourseTimeFeedback(
            @Valid @RequestBody CourseTimeFeedback data){
        try {
            UserDto userDto = this.getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (data.getStudentId() == null || data.getCourseTimeId() == null){
                return new ResultDTO(ErrorCode.PARAM_MISSING);
            }
            return courseClassService.putCourseTimeFeedback(data);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.errorResult(e.getMessage());
        }
    }

    @ApiOperation(value = "学生课程评价（课堂反馈）",notes = "{\"serviceUniqueId\":\"2022070717096750\",\"studentId\":1272392,\"likeability\":1,\"satisficing\":9,\"interact\":9,\"teaching\":9,\"likeTeacher\":1,\"praise\":1,\"oftenAskQuestions\":1,\"share\":1,\"learnAgain\":1}")
    @RequestMapping(value = "putCourseFeedback", method = RequestMethod.POST)
    public ResultDTO<Boolean> putCourseFeedback(
            @Valid @RequestBody CourseFeedback data){
        try {
            UserDto userDto = this.getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (data.getStudentId() == null || data.getServiceUniqueId() == null){
                return new ResultDTO(ErrorCode.PARAM_MISSING);
            }
            return courseClassService.putCourseFeedback(data);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.errorResult(e.getMessage());
        }
    }

    @ApiOperation(value = "获取教师课时反馈分页列表")
    @RequestMapping(value = "getTeacherCourseTimeFeedbackListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<TeacherCourseTimeFeedbackDto>> getTeacherCourseTimeFeedbackListByPage(
            @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId,
            @ApiParam(value = "只看孩子相关课程评价", required = false,defaultValue = "1") @RequestParam(name = "relatedMe", required = false) Boolean relatedMe,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize
    ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(studentId)){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            params.put("relatedMe", relatedMe);
            PageInfo<TeacherCourseTimeFeedbackDto> pageInfo = courseClassService.getTeacherCourseTimeFeedbackListByStudent(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "教师课时反馈点赞",notes = "{\"feedbackId\":1,\"studentId\":1272392}")
    @RequestMapping(value = "likeTeacherCourseTimeFeedback", method = RequestMethod.POST)
    public ResultDTO<Boolean> likeTeacherCourseTimeFeedback(
            @Valid @RequestBody TeacherCourseTimeFeedbackLike data
    ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(data.getStudentId())){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            if (data.getFeedbackId() == null){
                return new ResultDTO(ErrorCode.PARAM_MISSING);
            }
            return courseClassService.likeTeacherCourseTimeFeedback(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "教师课时反馈评论",notes = "{\"feedbackId\":1,\"studentId\":1272392,\"content\":\"评论评论\"}")
    @RequestMapping(value = "commentTeacherCourseTimeFeedback", method = RequestMethod.POST)
    public ResultDTO<Boolean> commentTeacherCourseTimeFeedback(
            @Valid @RequestBody TeacherCourseTimeFeedbackLike data
    ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(data.getStudentId())){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            if (StringUtils.isEmpty(data.getContent()) || data.getFeedbackId() == null){
                return new ResultDTO(ErrorCode.PARAM_MISSING);
            }
            return courseClassService.commentTeacherCourseTimeFeedback(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }
}